<template>
  <el-dialog title="绑定用户" :visible.sync="visible" width="800px">
    <div>
      <!--
      <el-transfer
        filterable
        :filter-method="filterMethod"
        filter-placeholder="请输入用户"
        v-model="selections"
        :data="tableData"
        :props="props"
        :titles="['可选用户', '已选用户']"
        :button-texts="['可选用户', '已选用户']"
        target-order="unshift"
        @change="updeletData"
        @left-check-change="leftcheck"
        @right-check-change="rightcheck"
      >
      </el-transfer>

      <el-divider content-position="left">以下为仿穿梭框</el-divider>
      -->
      <div class="el-transfer">
        <div class="el-transfer-panel" title="可选用户" buttontext="可选用户，已选用户" filterplaceholder="请输入用户名">
          <p class="el-transfer-panel__header" :class="{'is-indeterminate':leftAllSelected.indeterminate,'is-checked':leftAllSelected.checked}">
            <label class="el-checkbox">
              <span class="el-checkbox__input" :class="{'is-indeterminate':leftAllSelected.indeterminate,'is-checked':leftAllSelected.checked}">
                <span class="el-checkbox__inner"></span>
                <input type="checkbox" class="el-checkbox__original" @click="changeAllSelect('left')"/>
              </span>
              <span class="el-checkbox__label">
                可选用户
                <span>{{leftTempData.length}}/{{leftData.length}}</span>
              </span>
            </label>
          </p>
          <div class="el-transfer-panel__body">
            <div class="el-transfer-panel__filter el-input el-input--small el-input--prefix">
              <input type="text" v-model.trim="leftSearch" autocomplete="off" placeholder="请输入用户名" class="el-input__inner"/>
              <span class="el-input__prefix"><i class="el-input el-icon-search" style="margin:66% 66%;"></i></span>
            </div>
            <div role="group" class="el-checkbox-grop el-transfer-panel__list is-filterable" :class="{'display':!leftTip.display}">
              <label v-for="item in leftData" class="el-checkbox el-transfer-panel__item" :key="item.value" :class="{'is-checked':item.checked}">
                <span class="el-checkbox__input" :class="{'is-checked':item.checked}">
                  <span class="el-checkbox__inner" ></span>
                  <input type="checkbox" class="el-checkbox__original"  @click="changeChecked('left',item)" value="item.value"/>
                </span>
                <span class="el-checkbox__label">
                  <span>{{item.label}}</span>
                </span>
              </label>
            </div>
            <p class="el-transfer-panel__empty" :class="{'display':leftTip.display}">{{leftTip.text}}</p>
          </div>
        </div>

        <div class="el-transfer__buttons">
          <button @click="arryUpdate('left')" type="button" class="el-button el-button--primary el-transfer__button is-with-texts" :class="{'is-disabled':allowLeftBtn}">
            <span>
              <i class="el-icon-arrow-left"></i>
              <span>可选用户</span>
            </span>
          </button>
          <button @click="arryUpdate('right')" type="button" class="el-button el-button--primary el-transfer__button is-with-texts" :class="{'is-disabled':allowRightBtn}">
            <span>
              <i class="el-icon-arrow-right"></i>
              <span>已选用户</span>
            </span>
          </button>
        </div>

        <div class="el-transfer-panel" title="已选用户"  filterplaceholder="请输入用户名">
          <p class="el-transfer-panel__header">
            <label class="el-checkbox" :class="{'is-indeterminate':rightAllSelected.indeterminate,'is-checked':rightAllSelected.checked}">
              <span class="el-checkbox__input" :class="{'is-indeterminate':rightAllSelected.indeterminate,'is-checked':rightAllSelected.checked}">
                <span class="el-checkbox__inner"></span>
                <input type="checkbox" class="el-checkbox__original" @click="changeAllSelect('right')"/>
              </span>
              <span class="el-checkbox__label">
                已选用户
                <span>{{rightTempData.length}}/{{rightData.length}}</span>
              </span>
            </label>
          </p>
          <div class="el-transfer-panel__body">
            <div class="el-transfer-panel__filter el-input el-input--small el-input--prefix">
              <input type="text" v-model.trim="rightSearch" autocomplete="off" placeholder="请输入用户名" class="el-input__inner"/>
              <span class="el-input__prefix"><i class="el-input el-icon-search" style="margin:66% 66%;"></i></span>
            </div>
            <div role="group" class="el-checkbox-grop el-transfer-panel__list is-filterable" :class="{'display':!rightTip.display}">
              <label v-for="item in rightData" class="el-checkbox el-transfer-panel__item" :key="item.value" :class="{'is-checked':item.checked}">
                <span class="el-checkbox__input" :class="{'is-checked':item.checked}">
                  <span class="el-checkbox__inner" ></span>
                  <input type="checkbox" class="el-checkbox__original"  @click="changeChecked('right',item)" value="item.value"/>
                </span>
                <span class="el-checkbox__label">
                  <span>{{item.label}}</span>
                </span>
              </label>
            </div>
            <p class="el-transfer-panel__empty" :class="{'display':rightTip.display}">{{rightTip.text}}</p>
          </div>
        </div>

      </div>
    </div>

  </el-dialog>
</template>

<script>
export default {
  props: {
    dialogVisible: {
      type: Boolean,
      default: false,
    },
    width: {
      type: String,
      default: "80%",
    },
    row: {
      type: Object,
      default() {
        return {};
      },
    },
  },

  data() {
    return {
      org: {
        orgName: "",
        orgId: "",
      },
      tableData: [],
      tableIdData: [],
      tablenameDate:[],
      props: {
        key: "userName",
        label: "cnName",
      },
      selections: [],
      branchName:"",

      leftData: [],
      leftDataCopy: [],
      rightData: [],
      rightDataCopy: [],
      allowRightBtn: true,//右箭头不可用
      allowLeftBtn: true,//左箭头不可用
      leftTempData: [],
      rightTempData: [],
      leftSearch: "",
      rightSearch: "",
      leftAllSelected:{
        checked: false,
        indeterminate: false,
      },
      rightAllSelected:{
        checked: false,
        indeterminate: false,
      },
      leftTip: {
        isSearch: false,
        display: false,
        text: "无数据",
      },
      rightTip: {
        isSearch: false,
        display: false,
        text: "无数据",
      }
    };
  },
  computed: {
    visible: {
      get() {
        return this.dialogVisible;
      },
      set(val) {
        this.$emit("update:dialogVisible", val);
      },
    },
  },
  methods: {
    filterMethod(query, item) {
      return item.cnName.indexOf(query) > -1;
    },
    //查询用户
    getList() {
      this.tableData = [];
      this.leftData = []
      const data = {
        orgId: this.org.orgId,
      };
      // console.log(data)
      this.$http
        .get("/IAM/queryAddTeamUsers", { params: data })
        .then((res) => {
          console.log(res.data)
          for(let i = 0; i < res.data.length; i++){
            let isRight = this.rightDataCopy.find((element) => (element.value == res.data[i].userName));
            if(!isRight){
              this.leftData.push({
                label: res.data[i].userName,
                value: res.data[i].id,
                checked: false,
              })
            }
          }
          this.leftDataCopy = Object.assign([],this.leftData);
        });
    },

    //查询已分配用户
    showlist(arr) {
      this.tableData =arr || [];

      this.$http.get("/IAM/teamdto?id="+this.row.id)
        .then( res => {
          console.log(res)
          for(let i = 0; i < res.data.iamUserSet.length; i++){
            this.rightData.push({
              label: res.data.iamUserSet[i].userName,
              value: res.data.iamUserSet[i].id,
              checked: false,
            });
          }
          //this.rightDataCopy = Object.assign([],this.rightData);
        })
    },


    updeletData(value, direction, movedKeys) {
      let updatename = []
      for(let i = 0; i < this.tableData.length; i++) {
        for(let j = 0; j < movedKeys.length; j++) {
          if(this.tableData[i].userId == movedKeys[j]){
            updatename.push(this.tableData[i].userName)
            this.tableIdData.push(movedKeys[j])
            // this.selections.push(movedKeys[j])
          }
        }
      }
      let data = {
        updator: localStorage.getItem("User_Name"),
        userId: updatename,
        teamId: this.row.id||'9999',
        // ...this.selections
      };
      console.log(data)
      console.log(this.selections)
      if(direction == 'left'){

        this.$http.put("/IAM/deleteUserByTeam", data).then( res => {
          if (res.code == 200) {
            console.log(res)
            this.$message.success("操作成功");
            this.leftTempData = [];
            this.rightTempData = [];
          } else {
            this.$message.error("操作失败");
          }
        })
      } else {
        this.$http.put("/IAM/updateCmTeamUser",data).then((res) => {
          if (res.code == 200) {
            this.$message.success("操作成功");
            this.leftTempData = [];
            this.rightTempData = [];
          } else {
            this.$message.error("操作失败");
          }
        });
      }
      // console.log(this.tableData)
    },
    // 左侧列表元素选择框发生变化
    leftcheck() {

    },
    // 右侧列表元素选择框发生变化
    rightcheck() {

    },
    deleteUserByTeam(data) {
      this.$http.put("/IAM/deleteUserByTeam", data).then( res => {
        if (res.code == 200) {
          console.log(res)
          this.$message.success("操作成功");
        } else {
          this.$message.error("操作失败");
        }
      })
    },
    updateCmTeamUser(data) {
      this.$http.put("/IAM/updateCmTeamUser",data).then((res) => {
        if (res.code == 200) {
          this.$message.success("操作成功");
        } else {
          this.$message.error("操作失败");
        }
      });
    },

    handleSelect(val) {
      this.org.orgId = val.branchId;
      this.org.orgName = val.branchName;
      // console.log(this.org)
    },
    //切换选中状态
    changeChecked(direct,item){
      console.log("direct,,",direct,":::item,",item);
      if(direct=="left"){
        if(item.checked){
          item.checked = false;
          this.removeChecked(direct,item);
        }else{
          item.checked = true;
          this.leftTempData.push(item);
        }
      }else{
        if(item.checked){
          item.checked = false;
          this.removeChecked(direct,item);
        }else{
          item.checked = true;
          this.rightTempData.push(item);
        }
      }
    },
    //从临时data中删除
    removeChecked(direct,item){
      if(direct=="left"){
        let itemIndex = this.leftTempData.indexOf(item);
        if(itemIndex>=0){
          this.leftTempData.splice(itemIndex,1);
        }
      }else{
        let itemIndex = this.rightTempData.indexOf(item);
        if(itemIndex>=0){
          this.rightTempData.splice(itemIndex,1);
        }
      }
    },
    //调用接口更新后台数据
    updateDB(direct){
      let flag = true;
      let vals= [];
      let url = "";
      if(direct == "left"){
        this.rightTempData.forEach((item,index) => {
          vals.push(item.value);
        })
        url = "/IAM/deleteUserByTeam";
      }else{
        this.leftTempData.forEach((item,index) => {
          vals.push(item.value);
        })
        url = "/IAM/updateCmTeamUser";
      }

      let data = {
        updator: this.$store.getters.userName,
        userId: vals,
        teamId: this.row.id||'9999',
      };
      console.log("data=",data);
      this.$http.put(url,data).then((res) => {
        if (res.code == 200) {
          this.$message.success("操作成功");
          flag = true;
        } else {
          this.$message.error("操作失败");
          flag = false;
        }
      });

      return flag;
    },
    arryUpdate(direct){
      if(!this.updateDB(direct)){
        return ;
      }
      if(direct=="left"){

        this.rightTempData.forEach((item,index) => {
          let sss = this.rightData.indexOf(item);
          if(sss>=0){
            let obj = Object.assign({},item);
            obj.checked= false;
            this.leftData.push(obj);
            this.rightData.splice(sss,1);
          }
        })
        this.rightTempData = [];

      }else{
        this.leftTempData.forEach((item,index) => {
          let sss = this.leftData.indexOf(item);
          if(sss>=0){
            let obj = Object.assign({},item);
            obj.checked = false;
            this.rightData.push(obj);
            this.leftData.splice(sss,1);
          }
        })
        this.leftTempData = [];
      }

    },
    //切换左右全选的状态
    changeAllSelect(direct){
      if(direct=="left"){
        if(this.leftAllSelected.checked){
          this.leftAllSelected.checked = false;
          this.selectedAll(direct,false);
        }else{
          this.leftAllSelected.checked = true;
          this.selectedAll(direct,true);
        }
      } else {
        if(this.rightAllSelected.checked){
          this.rightAllSelected.checked = false;
          this.selectedAll(direct,false);
        }else{
          this.rightAllSelected.checked = true;
          this.selectedAll(direct,true);
        }
      }
    },
    selectedAll(direct,checked){
      if(direct=="left"){
        this.leftTempData = [];
        this.leftData.forEach((item,index) => {
          item.checked = checked;
          if(checked){
            this.leftTempData.push(item);
          }
        });
      } else {
        this.rightTempData = [];
        this.rightData.forEach((item,index) => {
          item.checked = checked;
          if(checked){
            this.rightTempData.push(item);
          }
        });
      }
    }
  },
  watch:{
    rightData: {
      handler: function(){

        if(this.rightData.length > this.rightTempData.length && this.rightTempData.length > 0){
          this.rightAllSelected.indeterminate = true;
          this.rightAllSelected.checked = false;
        }else if(this.rightData.length == this.rightTempData.length && this.rightTempData.length > 0){
          this.rightAllSelected.indeterminate = false;
          this.rightAllSelected.checked = true;
        }else{
          this.rightAllSelected.indeterminate = false;
          this.rightAllSelected.checked = false;
        }
        if(this.rightData.length==0){
          this.rightTip.display = false;
          if(this.rightTip.isSearch){
            this.rightTip.text = "无匹配数据";
          }else {
            this.rightTip.text = "无数据";
          }
        }else{
          this.rightTip.display = true;
        }
      },
      deep: true
    },
    leftData: {
      handler: function(){

        if(this.leftData.length > this.leftTempData.length && this.leftTempData.length > 0){
          this.leftAllSelected.indeterminate = true;
          this.leftAllSelected.checked = false;
        }else if(this.leftData.length == this.leftTempData.length && this.leftTempData.length > 0){
          this.leftAllSelected.indeterminate = false;
          this.leftAllSelected.checked = true;
        }else{
          this.leftAllSelected.indeterminate = false;
          this.leftAllSelected.checked = false;
        }

        if(this.leftData.length==0){
          this.leftTip.display = false;
          if(this.leftTip.isSearch){
            this.leftTip.text = "无匹配数据";
          }else {
            this.leftTip.text = "无数据";
          }
        }else {
          this.leftTip.display = true;
        }
      },
      deep: true
    },

    rightTempData: {
      handler: function(){
        if(this.rightTempData.length>0){
          this.allowLeftBtn = false;
        }else{
          this.allowLeftBtn = true;
        }

        if(this.rightData.length > this.rightTempData.length && this.rightTempData.length > 0){
          this.rightAllSelected.indeterminate = true;
          this.rightAllSelected.checked = false;
        }else if(this.rightData.length == this.rightTempData.length && this.rightTempData.length > 0){
          this.rightAllSelected.indeterminate = false;
          this.rightAllSelected.checked = true;
        }else{
          this.rightAllSelected.indeterminate = false;
          this.rightAllSelected.checked = false;
        }
      },
      deep: true
    },
    leftTempData: {
      handler: function(){
        if(this.leftTempData.length>0){
          this.allowRightBtn = false;
        }else{
          this.allowRightBtn = true;
        }

        if(this.leftData.length > this.leftTempData.length && this.leftTempData.length > 0){
          this.leftAllSelected.indeterminate = true;
          this.leftAllSelected.checked = false;
        }else if(this.leftData.length == this.leftTempData.length && this.leftTempData.length > 0){
          this.leftAllSelected.indeterminate = false;
          this.leftAllSelected.checked = true;
        }else{
          this.leftAllSelected.indeterminate = false;
          this.leftAllSelected.checked = false;
        }
      },
      deep: true
    },
    leftSearch: {
      handler: function(){
        if(this.leftSearch){
          let arr = [];
          this.leftDataCopy.forEach((item,index) => {
            if(item.label.indexOf(this.leftSearch)>-1){
              arr.push(item);
            }
          });
          this.leftData = arr;
          this.leftTip.isSearch = true;
        }else{
          this.leftData = this.leftDataCopy;
          this.leftTip.isSearch = false;
        }
      },
      deep: true
    },
    rightSearch: {
      handler: function(){
        if(this.rightSearch){
          let arr = [];
          this.rightDataCopy.forEach((item,index) => {
            if(item.label.indexOf(this.rightSearch)>-1){
              arr.push(item);
            }
          });
          this.rightData = arr;
          this.rightTip.isSearch = true;
        }else{
          this.rightData = this.rightDataCopy;
          this.rightTip.isSearch = false;
        }
      },
      deep: true
    }
  },
  created() {
    this.showlist()
    this.getList()
  },
};
</script>

<style scoped>
.display {
  display: none;
}
</style>
